import Vue from 'vue'
import { login, logout } from '@/api/login'
import { ACCESS_TOKEN, USER_NAME, USER_INFO } from '@/store/mutation-types'

const user = {
  state: {
    token: '',
    username: '',
    realname: '',
    avatar: '',
    info: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { username, realname }) => {
      if (username) state.username = username
      if (realname) state.realname = realname
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_INFO: (state, info) => {
      state.info = info
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then(response => {
            if (response.code == '200') {
              const result = response.result
              const userInfo = result.userInfo
              const expire = 7 * 24 * 60 * 60 * 1000
              Vue.ls.set(ACCESS_TOKEN, result.token, expire)
              Vue.ls.set(USER_NAME, userInfo.username, expire)
              Vue.ls.set(USER_INFO, userInfo, expire)
              commit('SET_TOKEN', result.token)
              commit('SET_INFO', userInfo)
              commit('SET_NAME', {
                username: userInfo.username,
                realname: userInfo.realname
              })
              commit('SET_AVATAR', userInfo.avatar)
              resolve(response)
            } else {
              reject(response)
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 登出
    Logout({ commit, state }) {
      return new Promise(resolve => {
        let logoutToken = state.token
        commit('SET_TOKEN', '')
        Vue.ls.remove(ACCESS_TOKEN)
        logout(logoutToken)
          .then(() => {
            resolve()
          })
          .catch(() => {
            resolve()
          })
      })
    }
  }
}

export default user
